package com.ojoin.ojoin.eb_spider.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.domain.AlipayAccount;
import com.ojoin.ojoin.eb_spider.domain.AlipayCheckException;
import com.ojoin.ojoin.eb_spider.domain.EmailMessage;
import com.ojoin.ojoin.eb_spider.service.AlipayCheckExceptionService;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;

@Service
public class AlipayCheckExceptionServiceImpl implements
		AlipayCheckExceptionService {

	private Logger log = LoggerFactory
			.getLogger(AlipayCheckExceptionServiceImpl.class);
	
	@Override
	public boolean isSend(Map<String, AlipayCheckException> map,
			List<AlipayAccount> lists) {

		boolean needSend = true;

		if (CommonUtils.isEmpty(map)) {
			return false;
		} else {
			Iterator<AlipayAccount> it = lists.iterator();
			while (it.hasNext()) {
				AlipayAccount ac = it.next();
				if (CommonUtils.isEmpty(map.get(ac.getUsername()))) {
					return false;
				} else {
					AlipayCheckException cacheac = map.get(ac.getUsername());
					
					LogUtils.info(log, "[ac.getAlipayCheckException().contain(cacheac):%s]" +
							"       ----[cacheac.getTmallUnpaySettleorder():%s,ac.getAlipayCheckException().getTmallUnpaySettleorder():%s]" +
							"       ----[ac.getAlipayCheckException().getAmountInArrear():%s,cacheac.getAmountInArrear():%s]",
							             ac.getAlipayCheckException().contain(cacheac),cacheac.getTmallUnpaySettleorder(),
							             ac.getAlipayCheckException().getTmallUnpaySettleorder(),
							             ac.getAlipayCheckException().getAmountInArrear(),
							             cacheac.getAmountInArrear()
							             );
					
					if (!ac.getAlipayCheckException().contain(cacheac) || !CommonUtils.isEqual(cacheac.getTmallUnpaySettleorder(), ac.getAlipayCheckException().getTmallUnpaySettleorder()) ||  !CommonUtils.isEqual(ac.getAlipayCheckException().getAmountInArrear(),cacheac.getAmountInArrear())) {
						return false;
					}
				}
			}
		}

		return needSend;
	}

	@Override
	public Map<String, AlipayCheckException> getCache(EmailMessage emailMessage) {
		if (CommonUtils.isEmpty(emailMessage)) {
			return null;
		}
		List<AlipayAccount> lists = emailMessage.getAlipayAccounts();

		Map<String, AlipayCheckException> map = new HashMap<String, AlipayCheckException>();

		if (!CommonUtils.isEmpty(lists)) {
			Iterator<AlipayAccount> it = lists.iterator();
			while (it.hasNext()) {
				AlipayAccount ac = it.next();
				map.put(ac.getUsername(), ac.getAlipayCheckException());
			}
		}

		return map;
	}

	@Override
	public boolean needToSend(boolean needCheck,
			AlipayCheckException alipayCheckException,
			AlipayCheckException stand) {

		if (needCheck) {
			if (CommonUtils.isEmpty(alipayCheckException.getLogIn())) {
				return true;
			} else if (alipayCheckException.getLogIn().equals("失败")) {
				return true;
			}

			if (CommonUtils.isEmpty(alipayCheckException.getBalancePay())) {
				return true;
			} else if (alipayCheckException.getBalancePay().equals("开")) {
				return true;
			}

			if (CommonUtils.isEmpty(alipayCheckException.getWirelessPay())) {

				return true;
			} else if (alipayCheckException.getWirelessPay().equals("开")) {
				return true;
			}

			if (CommonUtils.isEmpty(alipayCheckException.getRelations())) {
				return true;
			} else if (alipayCheckException.getRelations().equals(stand.getRelations())) {
				return true;
			}

			// TODO
			if (CommonUtils.isEmpty(alipayCheckException.getBoundCard())) {
				return true;
			} else if (!alipayCheckException.getBoundCard().equals(
					stand.getBoundCard())) {
				return true;
			}

			if (CommonUtils.isEmpty(alipayCheckException.getWithdrawDeposit())) {
				return true;
			} else if (!alipayCheckException.getWithdrawDeposit().equals(stand.getWithdrawDeposit())) {
				return true;
			}
			
			if (CommonUtils.isEmpty(alipayCheckException.getAmountInArrear())) {
				return true;
			} else if (alipayCheckException.getAmountInArrear().compareTo(stand.getAmountInArrear()) == 0 ) {
				return true;
			}
			
		}

		return false;
	}

/*	@Override
	public boolean initSendMailStyle(boolean needCheck,
			AlipayCheckException alipayCheckException,
			AlipayCheckException stand) {
		boolean needToSend = true;

		if (needCheck) {
			

			

			if (CommonUtils.isEmpty(alipayCheckException.getWirelessPay())) {
				alipayCheckException.setWirelessPay(this.getHtmlStyle("red",
						"抓取异常"));
			} else if (alipayCheckException.getWirelessPay().equals("开")) {
				alipayCheckException.setWirelessPay(this.getHtmlStyle("red",
						alipayCheckException.getWirelessPay()));
			} else {
				alipayCheckException.setWirelessPay(this
						.getHtmlStyle(alipayCheckException.getWirelessPay()));
			}

			

			

		return needToSend;
	}*/

	public String getHtmlFontStyle(String color, String content) {
		return "<font style='color:" + color + "'>" + content + "</font></br>";
	}

	public String getHtmlFontStyle(String content) {
		return "<font>" + content + "</font></br>";
	}

	public String getHtmlStyle(String color, String content) {
		return "<td style='color:" + color + "'>" + content + "</td>";
	}

	public String getHtmlStyle(String color, List<String> content) {
		return "<td style='color:" + color + "'>" + content + "</td>";
	}

	public String getHtmlStyle(List<String> content) {
		return "<td>" + content + "</td>";
	}

	public String getHtmlStyle(String content) {
		return getHtmlStyle("", content);
	}

	public String getHtmlStyle() {
		return getHtmlStyle("", "");
	}

	public String getHtmlFontStyle() {
		return getHtmlFontStyle("", "");
	}

	@Override
	public AlipayCheckException getStandard(String uname)
			throws DocumentException {

		InputStream in = AlipayCheckExceptionServiceImpl.class
				.getResourceAsStream("/alipayRule.xml");
		return getAlipayCheckException(in, uname);
	}

	@Override
	public AlipayCheckException saveStandard(String uname,
			AlipayCheckException alipayCheckException) {
		InputStream in = AlipayCheckExceptionServiceImpl.class
				.getResourceAsStream("/alipayRule.xml");

		return saveAlipayCheckException(in, uname);
	}

	public AlipayCheckException saveAlipayCheckException(InputStream in,
			String uname) {
		AlipayCheckException alipayCheckException = null;
		/*
		 * AlipayCheckException alipayCheckException = new
		 * AlipayCheckException(); SAXReader saxReader = new SAXReader();
		 * 
		 * try { Document document = saxReader.read(in); Element employees =
		 * document.getRootElement();
		 * 
		 * Iterator i = employees.elementIterator();
		 * 
		 * while (i.hasNext()) { Element employee = (Element) i.next();
		 * Attribute at = employee.attribute("username"); if
		 * (at.getValue().equals(uname)) {
		 * if(!CommonUtils.isEmpty(alipayCheckException.getBoundCard())){
		 * employee
		 * .element("boundCard").setText(alipayCheckException.getBoundCard());
		 * 
		 * }
		 * if(!CommonUtils.isEmpty(alipayCheckException.getWithdrawDeposit())){
		 * employee.element("withdrawDeposit").setText(alipayCheckException.
		 * getWithdrawDeposit());
		 * 
		 * }
		 * 
		 * 
		 * } }
		 * 
		 * OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter
		 * writer = new XMLWriter(new FileOutputStream(fileName),format);
		 * writer.write(document); writer.close();
		 * 
		 * } catch (DocumentException e) { System.out.println(e.getMessage()); }
		 * catch (UnsupportedEncodingException e) { // TODO Auto-generated catch
		 * block e.printStackTrace(); } catch (FileNotFoundException e) { //
		 * TODO Auto-generated catch block e.printStackTrace(); } catch
		 * (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */

		return alipayCheckException;
	}

	public AlipayCheckException getAlipayCheckException(InputStream in,
			String uname) throws DocumentException {
		AlipayCheckException alipayCheckException = null ;
		SAXReader saxReader = new SAXReader();

		Document document = saxReader.read(in);
		Element employees = document.getRootElement();

		Iterator i = employees.elementIterator();

		while (i.hasNext()) {
			Element employee = (Element) i.next();

			String name = employee.element("username").getText();
			if (name.equals(uname)) {
				
				String boundCard = employee.element("boundCard").getText();
				String checkedStartTime = employee.element("checkedStartTime")
						.getText();

				String availableBalanceStartingValue = employee.element("availableBalanceStartingValue")
						.getText();
				
				String disableBalanceStartingValue = employee.element("disableBalanceStartingValue")
						.getText();
				 
				alipayCheckException = new AlipayCheckException(Long.valueOf(availableBalanceStartingValue),Long.valueOf(disableBalanceStartingValue));
				
				alipayCheckException.getBoundCard().add(boundCard);
				alipayCheckException.setCheckedStartTime(TimeUtils
						.getDate(checkedStartTime));
				
		
				
			}
		}

		return alipayCheckException;
	}

	public static void main(String[] args) {

		AlipayCheckExceptionServiceImpl.class.getResource("alipayRule.xml");
		AlipayCheckExceptionServiceImpl.class.getResource("/alipayRule.xml");
		ClassLoader.getSystemResource("alipayRule.xml");
	}
}
